require('../mocks/co-wechat-oauth');
const urllib = require('url');
const assert = require('assert');
const querystring = require('querystring');

module.exports = async function loginWeixin(app) {
    const r1 = await app.httpRequest()
        .get('/user/login?r=/user/info')
        .expect(302);
    const red1 = urllib.parse(r1.headers.location, true);
    assert(red1.host === 'co-wechat-oauth-mock');
    assert(red1.query.scope === 'snsapi_userinfo');
    assert(red1.pathname === '/getAuthorizeURL');
    const red1red = urllib.parse(red1.query.redirect, true);
    red1red.query.code = 'MOCKCODE';
    red1red.search = '?' + querystring.stringify(red1red.query);
    
    const r2 = await app.httpRequest()
        .get(`${red1red.pathname}${red1red.search}`)
        .expect(302);
    let cookies = r2.headers['set-cookie'];
    if (!Array.isArray(cookies)) {
        cookies = [cookies];
    }
    const match = /(EGG_SESS=[^;]+);/.exec(cookies.find(cookie => cookie.startsWith('EGG_SESS=')));
    assert(match && match[1]);
    return match[1];
}